import asyncio
from AdvancedBLEScanner import AdvancedBLEScanner

# 使用示例
async def main():
    scanner = AdvancedBLEScanner()

    # 如果是Windows，显示调试信息
    if scanner.is_windows:
        await scanner.debug_windows_bluetooth()

    # 设置连接状态回调
    def on_connected(device_address):
        print(f"🎉 回调: 设备 {device_address} 已连接")

    def on_disconnected(device_address):
        print(f"🔌 回调: 设备 {device_address} 已断开")

    def on_connection_failed(device_address, error):
        print(f"❌ 回调: 设备 {device_address} 连接失败: {error}")

    scanner.set_connection_callbacks(on_connected, on_disconnected, on_connection_failed)

    # 设置过滤条件
    scanner.set_filter(
        name_prefixes=["AJ_"],
        rssi_threshold=-80
    )

    try:
        # 1. 扫描设备
        await scanner.scan_with_filters(duration=10)

        # 2. 显示设备列表供用户选择
        device_list = scanner.print_device_list()

        if not device_list:
            print("没有找到匹配的设备")
            return

        # 3. 用户选择设备
        try:
            choice = int(input("\n请选择要连接的设备编号: ")) - 1
            if 0 <= choice < len(device_list):
                selected_address, device_info = device_list[choice]
                print(f"已选择: {device_info['name']} ({selected_address})")
            else:
                print("❌ 无效的选择")
                return
        except ValueError:
            print("❌ 请输入有效的数字")
            return

        # 4. 连接设备
        client = await scanner.connect_with_retry(selected_address, max_retries=3)

        if client and client.is_connected:
            print("\n🎉 连接成功！可以开始BLE通讯")

            # 启用UART通知
            uart_tx_uuid = scanner.UUID_UART_TX

            # 确保使用正确参数数量的回调函数
            await scanner.start_notifications(uart_tx_uuid, scanner._add_uart_data)

            # 启动监控线程
            scanner.start_monitoring_threads()

            # 简化的交互菜单
            while scanner.running:
                print("\n" + "=" * 30)
                print("BLE设备操作菜单")
                print("=" * 30)
                print("1. 显示服务列表")
                print("2. 读取特征值")
                print("3. 写入特征值")
                print("4. 显示UART数据记录")
                print("5. 显示当前状态")
                print("6. 手动重连")
                print("7. 清空UART数据")
                print("8. 显示解析数据")
                print("9. 重置错误计数")
                print("10. 显示设备连接历史")
                print("0. 退出程序")
                print("按ESC键可随时退出")

                try:
                    # 使用异步输入避免阻塞
                    action = await asyncio.get_event_loop().run_in_executor(
                        None, input, "请选择: "
                    )
                    action = action.strip()

                    if action == "1":
                        await scanner.display_services()
                    elif action == "2":
                        char_uuid = input("请输入特征UUID: ").strip()
                        await scanner.read_characteristic(char_uuid)
                    elif action == "3":
                        char_uuid = input("请输入特征UUID: ").strip()
                        data = input("请输入要写入的数据(十六进制或文本): ").strip()
                        await scanner.write_characteristic(char_uuid, data)
                    elif action == "4":
                        # 使用新的专用方法显示UART数据
                        await scanner.display_uart_data()
                    elif action == "5":
                        print(f"\n当前状态:")
                        print(f"  连接状态: {'✅ 已连接' if scanner.connection_status else '❌ 已断开'}")
                        print(f"  电池电量: {scanner.battery_level if scanner.battery_level is not None else '未知'}%")
                        print(f"  UART数据接收: {scanner.get_uart_data_count()} 条")
                        print(f"  重连尝试: {scanner.reconnect_attempts}/{scanner.max_reconnect_attempts}")
                    elif action == "6":
                        if scanner.current_device_address:
                            print("手动重连...")
                            await scanner.connect_to_device(scanner.current_device_address)
                        else:
                            print("没有已知的设备地址")
                    elif action == "7":
                        scanner.clear_uart_data()
                        print("✅ UART数据已清空")
                    elif action == "8":  # 显示解析数据
                        await scanner.display_parsed_data()
                    elif action == "9":  # 重置错误计数
                        scanner.uart_parser.reset_errors()
                    elif action == "10":  # 显示设备连接历史
                        await scanner.display_device_history()
                    elif action == "0":
                        await scanner.disconnect()
                        break
                    else:
                        print("❌ 无效选择")

                    # 添加一个小延迟，让输出更清晰
                    await asyncio.sleep(0.1)

                except Exception as e:
                    print(f"输入错误: {e}")

        else:
            print("❌ 无法连接到设备")

    except KeyboardInterrupt:
        print("\n用户中断程序")
        await scanner.disconnect()
    except Exception as e:
        print(f"❌ 程序错误: {e}")
        await scanner.disconnect()


if __name__ == "__main__":
    # 检查keyboard库是否可用

    asyncio.run(main())